package main

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/elift/fid"
	"gitee.com/elift/utils.go/tools"
	"github.com/Sirupsen/logrus"
)

func main() {
	f := fid.New()
	f.InstallController(&UserController{})
	f.InstallController(&ManageController{})
	f.Start()
}

type UserController struct {
	BaseController
}

func (u *UserController) PassAuthorizationPaths() []string {
	return []string{
		"SCLogin",
	}
}

func (u *UserController) SCTest() (string, fid.APIError) {
	return "test:" + u.User.Name, fid.ErrNone
}

func (u *UserController) SCLogin() (string, fid.APIError) {
	u.Login(&User{
		Id:         "id001",
		Name:       "张三",
		CreateTime: time.Now(),
	})
	fmt.Println("login")
	return "登录成功", fid.ErrNone
}

// /mmmm/test
func (u *UserController) SCAuth() (string, fid.APIError) {
	u.SetPrivileges("P001", "P004")
	return "auth", fid.ErrNone
}

// /mmmm/test
func (u *UserController) SCAll() (string, fid.APIError) {
	u.MustPrivilegeAll("P001", "P002", "P003")
	return "all pass", fid.ErrNone
}

// /mmmm/test
func (u *UserController) SCIn() (string, fid.APIError) {
	u.MustPrivilegeIn("P001", "P002", "P003")
	return "in pass", fid.ErrNone
}

func (u *UserController) SCLogout() (string, fid.APIError) {
	u.ClearUserWrapper()
	return "logout pass", fid.ErrNone
}

//RouterPrefix() string
type ManageController struct {
	fid.Controller
}

func (m *ManageController) RouterPrefix() string {
	return "mmmm"
}

// /mmmm/test
func (m *ManageController) SCTest() (string, fid.APIError) {
	return "manage test", fid.ErrNone
}

type BaseController struct {
	fid.Controller
	User *User
}

type User struct {
	Id         string
	Name       string
	CreateTime time.Time
}

func (b *BaseController) StartRequest() fid.APIError {
	b.Controller.StartRequest()
	if b.SessionUser != nil {
		user := User{}
		tools.JsonOut(b.SessionUser)
		err := json.Unmarshal(b.SessionUser.UserWrapper, &user)
		if err != nil {
			logrus.Error(err)
			return fid.ErrBadSession
		}
		b.User = &user
	}
	return fid.ErrNone
}

func (b *BaseController) Login(user *User) {
	dt, _ := json.Marshal(user)
	b.SetUserWrapper(dt)
}
